﻿
using System;
using SqlSugar;
using System.Threading.Tasks;
using System.Linq.Expressions;

using Oliving.Edge.Model;
using Oliving.Edge.Model.Dto;
using Oliving.Edge.Model.Models;
using Oliving.Edge.IRepository;
using Oliving.Edge.IRepository.UnitOfWork;
using Oliving.Edge.Repository.Base;
using Oliving.Edge.Model.Dto.DTSN;
using Oliving.Edge.Model.DTSN;
using Oliving.Edge.IRepository.DTSN;
using System.Collections.Generic;
using Oliving.Edge.Model.ViewModels.ReportDto;
using Oliving.Edge.Model.ViewModels.DTSN;

namespace Oliving.Edge.Repository.DTSN
{
    /// <summary>
    /// DTSN_CanningRecordRepository
    /// </summary>
    public class DTSN_CanningRecordRepository : BaseRepository<DTSN_CanningRecord>, IDTSN_CanningRecordRepository
    {
        public DTSN_CanningRecordRepository(IUnitOfWork unitOfWork) : base(unitOfWork)
        {
        }






        /// <summary>
        /// 自定义分页查询
        /// </summary>
        /// <param name="whereExpression">查询条件</param>
        /// <param name="pageIndex" > 页码（下标0）</param>
        /// <param name="pageSize" > 页大小</param>
        /// <param name="sortField" > 排序字段</param>
        /// <param name="sortOrder" > 排序顺序（asc/desc）</param>
        /// <returns></returns>
        public async Task<PageModel<DTSN_CanningRecordPageDto>> QueryPageList(
                Expression<Func<DTSN_CanningRecord, bool>> whereExpression,
                int pageIndex = 1, int pageSize = 20,
                string sortField = null, string sortOrder = null
                )
        {


            #region 排序

            string strOrderByFileds = null;

            if (!string.IsNullOrEmpty(sortField))
            {
                strOrderByFileds = sortField;
                if (sortOrder != null && sortOrder.ToLower().Contains("desc"))
                {
                    strOrderByFileds = strOrderByFileds + " desc";
                }
                else
                {
                    strOrderByFileds = strOrderByFileds + " asc";
                }
            }

            #endregion

            if (1 == 1)
            {
                #region 单表

                RefAsync<int> totalCount = 0;
                var list = await Db.Queryable<DTSN_CanningRecord>()
                         // .OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds)
                         .OrderByIF(true, " CR_BeginTime  desc  ")
                         .WhereIF(whereExpression != null, whereExpression)
                         .Select<DTSN_CanningRecordPageDto>()
                         .ToPageListAsync(pageIndex, pageSize, totalCount);

                int pageCount = (Math.Ceiling(totalCount.ObjToDecimal() / pageSize.ObjToDecimal())).ObjToInt();
                return new PageModel<DTSN_CanningRecordPageDto>()
                {
                    dataCount = totalCount,
                    pageCount = pageCount,
                    page = pageIndex,
                    PageSize = pageSize,
                    data = list
                };

                #endregion
            }

            {
                //var list = Db.Queryable<DTSN_Canning, DTSN_TongDao>
                //   ((c, td) => new object[] { JoinType.Left, c.Canning_TongDaoID == td.TD_ID })
                // //.OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds)
                // .WhereIF(whereExpression != null, whereExpression)
                // .GroupBy((c, td) => td.TD_Type)
                // .GroupBy((c, td) => Convert.ToDateTime(c.Canning_BeginTime).ToShortDateString())
                //   .Select((c, td) => new
                //   {
                //       date = Convert.ToDateTime(c.Canning_BeginTime).ToShortDateString(),
                //       type = td.TD_Type,
                //       sum = SqlFunc.AggregateSum(c.Canning_NetWeight)
                //   }).ToList();
            }


        }




        public async Task<List<ChartDto>> ReportChart(Expression<Func<DTSN_CanningRecord, bool>> whereExpression)
        {
            var list = Db.Queryable<DTSN_CanningRecord, DTSN_TongDao>
           ((c, td) => new object[] { JoinType.Left, c.CR_TongDaoCode == td.TD_Code })
           .WhereIF(whereExpression != null, whereExpression)

           // .GroupBy((c, td) => c.CR_Date)//, c.CR_Date  td.TD_Type ? 0,   && td.TD_Type
           // .GroupBy((c, td) => c.CR_Date)


           .GroupBy((c, td) => c.CR_Type)
           .GroupBy((c, td) => c.CR_Date)

             .Select((c, td) => new ChartDto
             {
                 date = (c.CR_Date),// Convert.ToDateTime
                 type = c.CR_Type,
                 sum = SqlFunc.AggregateSum(c.CR_LoadingCapacity)
             }).ToList();

            return list;
        }



        public async Task<List<DTSN_ReportTongDaoDto>> ReportTongDao(
            Expression<Func<DTSN_CanningRecord, bool>> whereExpression
           
            )
        {
            var list = Db.Queryable<DTSN_CanningRecord>()

           .WhereIF(whereExpression != null, whereExpression)
           
           .GroupBy((c) => c.CR_TongDaoCode)

            .Select((c) => new DTSN_ReportTongDaoDto
            {
                TongDaoCode = (c.CR_TongDaoCode),
                TongDaoCount = SqlFunc.AggregateCount(c.CR_TongDaoCode),
                SumWeight = SqlFunc.AggregateSum(c.CR_LoadingCapacity)
            }).ToList();

            return list;
        }

    }
}

